# -*- coding: utf-8 -*-
"""
保温杯中性策略3期 | 邢不行 | 2023分享会
author: 邢不行
微信: xbx6660
"""
import numpy as np


def signal(*args):
    df = args[0]
    n = args[1]
    factor_name = args[2]
    df['bbi'] = (df['close'].rolling(n, min_periods=1).mean() + df['close'].rolling(2 * n, min_periods=1).mean() + \
                df['close'].rolling(4 * n, min_periods=1).mean()) / 3
    df['bbi_bias'] = df['close'] / df['bbi']
    df['route_1'] = 2 * (df['high'] - df['low']) + (df['open'] - df['close'])
    df['route_2'] = 2 * (df['high'] - df['low']) + (df['close'] - df['open'])
    df.loc[df['route_1'] > df['route_2'], '盘中最短路径'] = df['route_2']
    df.loc[df['route_1'] <= df['route_2'], '盘中最短路径'] = df['route_1']
    df['最短路径_标准化'] = df['盘中最短路径'] / df['open']
    df['流动溢价'] = df['quote_volume'] / df['最短路径_标准化']
    del df['route_1']
    del df['route_2']
    del df['盘中最短路径']
    del df['最短路径_标准化']
    # 1.计算原始的因子
    df['_factor1h'] = df['流动溢价'].rolling(n, min_periods=2).std()*df['bbi_bias']
    del df['流动溢价']
    # 2.获取小时
    df['hour'] = df['candle_begin_time'].dt.hour

    # 3.单独分离出周期为6h，offset为3的因子
    df['_zero_time_factor'] = np.where(df['hour'] % 6 == 0, df['_factor1h'], np.nan)
    df[factor_name] = df['_zero_time_factor'].fillna(method='ffill')
    return df



